HowTo: Configure diginsight telemetry to the local text based streams

You can ottain a console log or file log with diginsight by means of the steps shown below.

The code snippets are available as working samples within the telemetry.samples repository.
Article HOWTO - Use Diginsight Samples.md: explores how we can use diginsight samples to test and understand integration of Diginsight telemetry in our own projects.

STEP 01 - Add a package reference to the package Diginsight.Diagnostics or Diginsight.Diagnostics.Log4Net

In the first step you can just add a diginsight reference to your code:
alt text reference to Diginsight.Diagnostics is needed for the Console log and Diginsight.Diagnostics.Log4Net is required to enable Log4Net File log.

STEP 02 - Configure logging within the Startup sequence

In the second step you can configure the startup sequence to enable diginsight log:

public static void Main(string[] args)
{
    var builder = WebApplication.CreateBuilder(args);
    var services = builder.Services;
    var configuration = builder.Configuration;
    var environment = builder.Environment;

    // Add logging providers
    services.AddObservability(configuration, environment);

    services.AddControllers();
    services.AddEndpointsApiExplorer();
    services.AddSwaggerGen();

    // Use diginsight service provider 
    // this enables telemetry initialization at service provider creation
    builder.Host.UseDiginsightServiceProvider(true);
    WebApplication app = builder.Build();

    if (app.Environment.IsDevelopment())
    {
        app.UseSwagger();
        app.UseSwaggerUI();
    }

    app.UseHttpsRedirection();

    app.UseAuthorization();

    app.MapControllers();

    app.Run();
}

in the code above: - AddObservability() is used to add log to the application Console and a log4net file log. - UseDiginsightServiceProvider() is used to activate diginsight during the service provider build() process.

Please note that AddObservability() is implemented as an extension method that calls AddLogging() with: - AddDiginsightConsole(): this methods configures the Console log provider with some formatting options alt text

  • AddDiginsightLog4Net(): this methods configures a rolling File log on the user profile folder. alt text


The code above loads telemety based on the Diginsight:Activities configuration section that includes the enabled ActivitySources and their LogBehavior.

"Diginsight": {
    "Activities": {
        "LogBehavior": "Show",
        "MeterName": "SampleWebAPI",
        "ActivitySources": {
        "Microsoft.AspNetCore": true,
        "System.Net.Http": true,
        "Experimental.*": false,
        "Diginsight.*": true,
        "SampleWebAPI": true
        },
        "LoggedActivityNames": {
        "System.Net.Http|System.Net.Http.HttpRequestOut": "Hide",
        "Microsoft.AspNetCore.Hosting.HttpRequestIn": "Hide"
        }
    }
}

Activities LogBehavior can be set to: - Show: the activity is logged. - Hide: the activity is not logged. - Truncate: the activity and all inner activities called within its scope are not logged.

STEP 03 - Add telemetry to code with StartMethodActivity() and ILogger Statements

We are now ready to add instrumentation to the code and make the application flow observable.

The snippet below shows how to add telemetry to the GetWeatherForecast() method of the WeatherForecastController class:

[HttpGet(Name = "GetWeatherForecast")]
public IEnumerable<WeatherForecast> Get()
{
    // send method START and END events with Observability.ActivitySource
    using var activity = Observability.ActivitySource.StartMethodActivity(logger);

    var randomTemperature = Random.Shared.Next(-20, 55);
    // add to logger.LogDebug to send a log event
    logger.LogDebug("randomTemperature: {randomTemperature}", randomTemperature);

    var res = Enumerable.Range(1, 5).Select(index => new WeatherForecast
    {
        Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
        TemperatureC = randomTemperature,
        Summary = Summaries[Random.Shared.Next(Summaries.Length)]
    }).ToArray();

    activity?.SetOutput(res);
    return res;
}

in the snippet above: - using var activity = Observability.ActivitySource.StartMethodActivity(logger); is added to provide observability of method start and end - logger.LogDebug("randomTemperature: {randomTemperature}", randomTemperature); is usd to log the randomTemperature value, during the method execution. - activity.SetOutput(result); is used to add the method result to the method END event.

STEP 04 - run your code and look at the resulting application flow

The image below shows the application flow generated by DoSomeWork method The image belpw shows the sample method execution, where - method start and end are logged with the Method name, - randomTemperature is logged as a standard variable value and - the method result is logged within the method END raw.

alt text

STEP 03 (Full) - Add telemetry for the startup sequence

The S01_01_SampleWebAPIWithStartupSequence sample shows an example WebApi where telemetry is enabled also for the full startup sequence.

An ObservabilityManager is created with a LoggerFactory to record telemetry events until the ASP.NET Core Service Provider creation.
When the Service Provider is created, the recorded startup telemetry is sent to the configured registered providers (eg. Console, Log4Net).
In case of Exceptions during the startup sequence, telemetry is flushed to the Console/log4net by means of an emergency service provider, managed by the Observability manager.

public static void Main(string[] args)
{
    // this enables sending telemetry for the startup sequence
    // telemetry is recorded until ServiceProvider creation
    // after that, recorded telemetry is sent to the configured registered providers
    // (eg. AzureMonitor, Console, Log4Net) 
    using var observabilityManager = new ObservabilityManager();
    ILogger logger = observabilityManager.LoggerFactory.CreateLogger(typeof(Program));
    Observability.LoggerFactory = observabilityManager.LoggerFactory;

    WebApplication app;
    using (var activity = Observability.ActivitySource.StartMethodActivity(logger, new { args }))
    {
        var builder = WebApplication.CreateBuilder(args);
        var services = builder.Services;
        var configuration = builder.Configuration;
        var environment = builder.Environment;

        // Add logging and opentelemetry providers
        services.AddObservability(configuration, environment, out IOpenTelemetryOptions openTelemetryOptions);

        // registers recorded telemetry for flush after ServiceProvider creation
        observabilityManager.AttachTo(services);

        services.AddControllers();
        services.AddEndpointsApiExplorer();
        services.AddSwaggerGen();

        // use diginsight service provider 
        // this enables telemetry initialization at service provider creation
        builder.Host.UseDiginsightServiceProvider(true);
        app = builder.Build();

        if (app.Environment.IsDevelopment())
        {
            app.UseSwagger();
            app.UseSwaggerUI();
        }

        app.UseHttpsRedirection();

        app.UseAuthorization();

        app.MapControllers();
    }

    app.Run();
}

STEP 04 (Full) - run your code and look at the resulting application flow

The image below shows the application flow generated by the startup sequence.
In particular, Program.Main() method is logged with registration details of AddObservability() method.
, alt text

Back to top